package org.zxyj.manage.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.zxyj.core.constants.Constants;
import org.zxyj.core.constants.Dict;
import org.zxyj.core.constants.Keys;
import org.zxyj.core.constants.SysParamsDict;
import org.zxyj.core.entity.Pagination;
import org.zxyj.core.entity.Result;
import org.zxyj.core.exception.ServiceException;
import org.zxyj.core.utils.Common;
import org.zxyj.core.utils.FileUtil;
import org.zxyj.core.utils.MessageUtil;
import org.zxyj.core.utils.UUIDUtils;
import org.zxyj.core.web.controller.BaseController;
import org.zxyj.manage.entity.Batch;
import org.zxyj.manage.entity.CourseTemplate;
import org.zxyj.manage.entity.CourseTemplateArea;
import org.zxyj.manage.entity.CourseTemplateTmxx;
import org.zxyj.manage.service.ICheckService;
import org.zxyj.manage.service.ICourseTemplateService;
import org.zxyj.manage.service.ICropService;
import org.zxyj.manage.service.IPointRecognitionService;
import org.zxyj.system.domain.User;

/**
 * 答卷模板设置
    * @ClassName: CourseTemplateController
    * @author liuyong
    * @date 2016年7月7日
 */
@Controller
@RequestMapping("/manage/courseTemplate")
public class CourseTemplateController extends BaseController{
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	//读取配置文件
    //private static PropertiesUtil configProp = PropertiesUtil.newInstance(Thread.currentThread().getContextClassLoader().getResource("").getPath() + "config/config.properties");
    
	@Autowired
	private ICourseTemplateService courseTemplateService;
	@Autowired
	private ICropService cropService;
	@Autowired
	private ICheckService checkService;
	@Autowired
	private IPointRecognitionService pointRecognitionService;
	
	@RequestMapping({"","/","/index"})
	public ModelAndView index(ModelAndView mv) {
		mv.setViewName(Views.LIST_VIEW);
		Map<String, Object> criteria = new HashMap<String, Object>();
		Object query_batch = getParaValue("query_batch");
		Object query_grade = getParaValue("query_grade");
		Object query_course = getParaValue("query_course");
		criteria.put("batchId", query_batch);
		criteria.put("gradeNo", query_grade);
		criteria.put("courseNo", query_course);
		User user = (User) Common.findUserSession();
		criteria.put("userId", user.getId());
		Pagination page = (Pagination) getRequestAttr("pagination");
		Pagination pagination = courseTemplateService.getListEntities(criteria, page);
		mv.addObject(Keys.KEY_PAGINATION, pagination);
		List<Map<String,Object>> batchs = courseTemplateService.getExamBatchs(criteria);
		mv.addObject("batchs", batchs);
		mv.addObject("query_batch", query_batch);
		mv.addObject("query_grade", query_grade);
		mv.addObject("query_course", query_course);
		/*mv.addObject("query_sfsy", query_sfsy);
		mv.addObject("query_ksrq", query_ksrq !=null?DateUtil.parse(query_ksrq+"", null):null);
		mv.addObject("query_jsrq", query_ksrq !=null?DateUtil.parse(query_jsrq+"", null):null);
		mv.addObject("sfsys", sysParamsService.listEntitiesByKey(Keys.STATUS));*/
		return mv;
	}
	
	/**
	 * 根据批次查询年级
	    * @Title: queryGradeByBatch
	    * @param @param params
	    * @param @return    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/queryGradeByBatch", method = RequestMethod.POST)
	public Map<String,Object> queryGradeByBatch(@RequestBody Map<String,Object> params){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("list", this.courseTemplateService.getExamGradeByBatch(params));
		return map;
	}
	
	/**
	 * 根据年级查询课程
	    * @Title: queryCourseByGrade
	    * @param @param params
	    * @param @return    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/queryCourseByGrade", method = RequestMethod.POST)
	public Map<String,Object> queryCourseByGrade(@RequestBody Map<String,Object> params){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("list", this.courseTemplateService.getExamCourseByGrade(params));
		return map;
	}
	
	/**
	 * 查询科目模板是否存在
	    * @Title: queryCourseTempIsExists
	    * @param @param params
	    * @param @return    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/queryCourseTempIsExists", method = RequestMethod.POST)
	public Map<String,Object> queryCourseTempIsExists(@RequestBody Map<String,Object> params){
		Map<String,Object> map = new HashMap<String,Object>();
		String resultCode = SysParamsDict.STATUS_CODE.FAIL.getValue();
		CourseTemplate entity = this.courseTemplateService.findEntity(params);
		if(null != entity){
			map.put("fileUrl", entity.getFileName());
			map.put("courseTemplateId", entity.getId());
			resultCode = SysParamsDict.STATUS_CODE.SUCCESS.getValue();
		}
		map.put("resultCode", resultCode);
		return map;
	}
	
	/**
	 * 跳转到文件上传页面
	    * @Title: uploadTemplate
	    * @param @param mv
	    * @param @return    参数
	    * @return ModelAndView    返回类型
	    * @throws
	 */
	@RequestMapping("/uploadTemplate")
	public ModelAndView uploadTemplate(ModelAndView mv) {
		mv.setViewName(Views.UPLOAD_VIEW);
		mv.addObject("batchId", getParaValue("batchId"));
		mv.addObject("gradeNo", getParaValue("gradeNo"));
		mv.addObject("courseNo", getParaValue("courseNo"));
		mv.addObject("zfmType", getParaValue("zfmType"));
		return mv;
	}
	
	/**
	 * 上传模板文件
	    * @Title: doUploadTemplate
	    * @param @param request
	    * @param @param files
	    * @param @return
	    * @param @throws IOException    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	@ResponseBody
	@RequestMapping("/uploadTemplate/exec")
	public Map<String,Object> doUploadTemplate(HttpServletRequest request, @RequestParam("files[]") MultipartFile[] files) throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		String dotChar = ".";
		String fileFormat = Dict.IMAGE_FORMAT.PNG;
		String resultCode = SysParamsDict.STATUS_CODE.FAIL.getValue();
		String sessionId = getParaValue("jsessionid");
		request.getSession().setAttribute("jsessionid",sessionId);
		//获取参数
		String batchId = getParaValue("batchId")==null?"":getParaValue("batchId");
        String gradeNo = getParaValue("gradeNo")==null?"":getParaValue("gradeNo");
        String courseNo = getParaValue("courseNo")==null?"":getParaValue("courseNo");
        Integer zfmType = getParaValue("zfmType")==null?null:Integer.parseInt(getParaValue("zfmType"));
        String courseTemplateIdOld = getParaValue("courseTemplateId")==null?"":getParaValue("courseTemplateId");//原模板记录id
		String courseTemplateId = "";
		
        //处理附件上传
		String fileDir = MessageUtil.getExtConfig("fj.course.template.url");//实际文件存放目录
		String fileTempDir = MessageUtil.getExtConfig("fj.temp.pic.url");//临时文件存放目录
		String relativePath = batchId+"/";
		String filePath = fileDir + relativePath; //真实目录名  
		//创建目录
		FileUtil.createDir(filePath);
        
        try{
	        for (MultipartFile f : files) {
	        	if (f != null && !f.isEmpty()) {
	        		long fileSize = f.getSize();
	        		String fileName = f.getOriginalFilename();
	        		String contentType = fileName.substring(fileName.lastIndexOf(dotChar)+1).toLowerCase();//检查文件后缀格式  
	        		String fileName1 = ""+System.currentTimeMillis();//创建文件唯一名称  
	        		 StringBuffer sbRealPath = new StringBuffer();  
	                 sbRealPath.append(filePath).append(fileName1).append(dotChar).append(contentType); //真实上传路径 
	                 String relativePathPng = relativePath + fileName1 + dotChar + fileFormat;//png图片相对路径
	                 relativePath = relativePath + fileName1 + dotChar +contentType;//tif图片相对路径
	                 File file = new File(sbRealPath.toString());//写入文件 
	        		 FileUtils.copyInputStreamToFile(f.getInputStream(), file);
	        		 
	        		 fileName1 += dotChar + fileFormat;//新文件名称
	        		 String outputPng="";
	        		 Map<String,Object> param = new HashMap<String,Object>();
	                 //如果文件格式是tif格式，则将tif文件转成png格式
	                 if(contentType.equalsIgnoreCase(Dict.IMAGE_FORMAT.TIF)){
	                     String tifUrl = fileDir + relativePath;//tif文件路径
	                     outputPng = fileDir + relativePathPng;//png格式文件输出路径
	                     String tempPicUrl = fileTempDir;//临时图片存放路径
	                     FileUtil.createDir(tempPicUrl);
	                     String imgName = UUIDUtils.UUID() + dotChar + fileFormat;
	                     if(zfmType==1){
	                     	//识别答卷定位点坐标
	                        int start_pos_x = Dict.DEFAULT_CROP_LEFT_SIZE.START_X;
	                        int start_pos_y = Dict.DEFAULT_CROP_LEFT_SIZE.START_Y;
	                        Map<String,Object> params = new HashMap<String,Object>();
	                        params.put("width", Dict.DEFAULT_CROP_LEFT_SIZE.WIDTH);
	                        params.put("height", Dict.DEFAULT_CROP_LEFT_SIZE.HEIGHT);
	                        params.put("start_x", Dict.DEFAULT_CROP_LEFT_SIZE.START_X);
	                        params.put("start_y", Dict.DEFAULT_CROP_LEFT_SIZE.START_Y);
	                        params.put("sourceUrl", tifUrl);
	                        BufferedImage image_pos = cropService.getCropImageBuffered(params);//读取文件流
	                        if(image_pos!=null){
	                            Map<String,Object> map_pos = pointRecognitionService.getAreaResult(image_pos,2);
	                            start_pos_x = Integer.parseInt(map_pos.get("start_x")+"");//图像内容实际起始点X
	                            start_pos_y = Integer.parseInt(map_pos.get("start_y")+"");//图像内容实际起始点Y
	                        }
	                         
	                        //对答卷进行偏正校正
	                        param.put("sourceUrl", tifUrl);
	                        param.put("destUrl", tempPicUrl);
	                        param.put("imgName", imgName);
	                        param.put("start_pos_x", start_pos_x);
	                        param.put("start_pos_y", start_pos_y);
	                        param.put("fileType", dotChar+fileFormat);
	                        outputPng = checkService.getBufferedResultForTempZm(param);
	                    }else if(zfmType==2){
	                    	param.put("sourceUrl", tifUrl);
	                        param.put("destUrl", tempPicUrl);
	                        param.put("imgName", imgName);
	                        param.put("start_pos_x", Dict.DEFAULT_POS.START_X);
	                        param.put("start_pos_y", Dict.DEFAULT_POS.START_Y);
	                        param.put("fileType", dotChar+fileFormat);
	                        outputPng = checkService.getBufferedResultForTempFm(param);
	                    }
	                }
	                 
	                //读取图片文件尺寸大小
	                int width = 0;
	                int height = 0;
	                BufferedImage image = cropService.readImageBuffered(outputPng);//读取文件流
	                if(image!=null){
	                    width = image.getWidth();
	                    height = image.getHeight();
	                }
	                 
	                //将文件记录写入数据表
	                courseTemplateId = UUIDUtils.UUID();
	                CourseTemplate entity = new CourseTemplate();
	                entity.setId(courseTemplateId);
	                Batch batch = new Batch();
	                batch.setId(batchId);
	                entity.setBatch(batch);
	                entity.setCourseNo(courseNo);
	                entity.setContentType(fileFormat);
	                entity.setFileName(fileName1);
	                entity.setFilePath(relativePathPng);
	                entity.setFileSize(fileSize);
	                entity.setGradeNo(gradeNo);
	                entity.setZfmType(zfmType);
	                entity.setImgHeight(height);
	                entity.setImgWidth(width);
	                entity.setOwner(courseNo);
	            	this.courseTemplateService.saveOrUpdateEntity(entity,courseTemplateIdOld);
	         		resultCode = SysParamsDict.STATUS_CODE.SUCCESS.getValue();
	        	}
	        }
            logger.info("save courseTemplate data is success!!! exec method is doUploadTemplate.");
        }catch(Exception ex){
        	logger.error("save courseTemplate data is fail!!! exec method is doUploadTemplate.", ex);
        }
        map.put("resultCode", resultCode);
        map.put("courseTemplateId", courseTemplateId);
        return map;
	}
	
	/**
	 * 跳转到模板编辑页面
	    * @Title: editCourseTemp
	    * @param @param mv
	    * @param @return    参数
	    * @return ModelAndView    返回类型
	    * @throws
	 */
	@RequestMapping("/editCourseTemp")
	public ModelAndView editCourseTemp(ModelAndView mv){
		mv.setViewName(Views.EDIT_VIEW);
		String courseTemplateId = getParaValue("courseTemplateId");//附件id
        int screen_width = Integer.parseInt(getParaValue("screen_width"));//屏幕宽度
        
        String fjUrl = "";//附件地址
        String sfsf ="false";//缩放缩放图像 false-不缩放  true-缩放
        //查询附件的保存地址
        Map<String,Object> criteria = new HashMap<String,Object>();
        criteria.put("id", courseTemplateId);
        CourseTemplate temp = this.courseTemplateService.findEntity(criteria);
        //查询该科目已保存的截图区域信息
        criteria.clear();
        criteria.put("owner", courseTemplateId);
        List<CourseTemplateArea> list1 = this.courseTemplateService.getCourseTemplateAreaList(criteria);
        fjUrl = temp.getFilePath();
        Integer img_width = temp.getImgWidth();
        Integer img_height = temp.getImgHeight();
        float width_bl = 1f;
        if(img_width > screen_width){
        	//图片宽度大于1500PX，将图像缩放一半尺寸显示
        	width_bl = Float.valueOf(screen_width) / img_width;
            img_width = (int) (img_width * width_bl);
            img_height = (int) (img_height * width_bl);
            sfsf = "true";
        }

        mv.addObject("img_width", img_width);
        mv.addObject("img_height", img_height);
        mv.addObject("width_bl", width_bl);
        mv.addObject("sfsf", sfsf);
        mv.addObject("fjUrl", fjUrl);
        mv.addObject("posList", list1);
        mv.addObject("courseTemplateId", courseTemplateId);
		return mv;
	}
	
	/**
	 * 跳转到所选区域截图坐标页面
	    * @Title: toCropPage
	    * @param @param mv
	    * @param @return    参数
	    * @return ModelAndView    返回类型
	    * @throws
	 */
	@RequestMapping("/toCropPage")
	public ModelAndView toCropPage(ModelAndView mv){
		mv.setViewName(Views.JCROP_INDEX_VIEW);
		String courseTemplateId = getParaValue("courseTemplateId");//附件id
		mv.addObject("px1", getParaValue("px1"));
		mv.addObject("px2", getParaValue("px2"));
		mv.addObject("py1", getParaValue("py1"));
		mv.addObject("py2", getParaValue("py2"));
		mv.addObject("posId", getParaValue("posId"));
		mv.addObject("sfsf", getParaValue("sfsf"));
		mv.addObject("img_width", getParaValue("img_width"));
		mv.addObject("img_height", getParaValue("img_height"));
		mv.addObject("width_bl", getParaValue("width_bl"));
		Map<String,Object> criteria = new HashMap<String,Object>();
		criteria.put("owner", courseTemplateId);
		mv.addObject("posList", this.courseTemplateService.getCourseTemplateAreaList(criteria));//查询该科目已保存的截图区域信息
		mv.addObject("courseTemplateId", courseTemplateId);
		mv.addObject("fjUrl" , getParaValue("fjUrl"));
		return mv;
	}
	
	/**
	 * 跳转到截图属性信息页面
	    * @Title: editAreaProp
	    * @param @param mv
	    * @param @return    参数
	    * @return ModelAndView    返回类型
	    * @throws
	 */
	@RequestMapping("/editAreaProp")
	public ModelAndView editAreaProp(ModelAndView mv){
		mv.setViewName(Views.EDIT_AREA_PROP_VIEW);
		String courseTemplateId = getParaValue("courseTemplateId");//模板id
		mv.addObject("x1", getParaValue("x1"));
		mv.addObject("x2", getParaValue("x2"));
		mv.addObject("y1", getParaValue("y1"));
		mv.addObject("y2", getParaValue("y2"));
		mv.addObject("sfsf", getParaValue("sfsf"));
		mv.addObject("width_bl", getParaValue("width_bl"));
		mv.addObject("type" , getParaValue("type"));
        String posId = getParaValue("posId");//截图id
        mv.addObject("posId" , posId);
        CourseTemplateArea area = new CourseTemplateArea();
        List<CourseTemplateTmxx> tmList = new ArrayList<CourseTemplateTmxx>();
        if(!StringUtils.isEmpty(posId)){
            //查询记录详细信息
        	Map<String,Object> criteria = new HashMap<String,Object>();
            criteria.put("id", posId);
            area = this.courseTemplateService.findAreaEntity(criteria);
            
            //查询题目信息
            criteria.clear();
            criteria.put("owner", posId);
            tmList = this.courseTemplateService.getTmxxListEntities(criteria);
        }
        mv.addObject("entity", area);
        mv.addObject("tmList",tmList);
        mv.addObject("courseTemplateId", courseTemplateId);
		return mv;
	}
	
	/**
	 * 删除科目模板区域
	    * @Title: doDeleteCropInfo
	    * @param @return    参数
	    * @return Result<?>    返回类型
	    * @throws
	 */
	@ResponseBody
	@RequestMapping("/deleteArea/exec")
	public Result<?> doDeleteArea(@RequestBody Map<String,Object> criteria) {
		Result<?> result = new Result<String>();
		try {
			this.courseTemplateService.deleteAreaEntity(criteria);
			result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
		} catch (ServiceException e) {
			result.setResultCode(e.getErrorNo());
		}
		return result;
	}
	
	/**
	 * 删除科目模板区域题目
	    * @Title: doDeleteCropInfo
	    * @param @return    参数
	    * @return Result<?>    返回类型
	    * @throws
	 */
	@ResponseBody
	@RequestMapping("/deleteCropInfo/exec")
	public Result<?> doDeleteTmxx() {
		Result<?> result = new Result<String>();
		try {
			Map<String,Object> criteria = new HashMap<String,Object>();
        	criteria.put("id", getParaValue("id"));
			this.courseTemplateService.deleteTmxxEntity(criteria);
			result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
		} catch (ServiceException e) {
			result.setResultCode(e.getErrorNo());
		}
		return result;
	}
	
	/**
	 * @throws IOException 
	 * 保存截图信息
	    * @Title: doSaveCropInfo
	    * @param @return    参数
	    * @return Result<?>    返回类型
	    * @throws
	 */
	@ResponseBody
	@RequestMapping("/saveCropInfo/exec")
	public Result<?> doSaveCropInfo() throws IOException {
		Result<?> result = new Result<String>();
		Map<String,Object> criteria = new HashMap<String,Object>();
		Map<String,Object> params = new HashMap<String,Object>();
		Map<String,Object> criteria1 = new HashMap<String,Object>();
		Map<String,Object> criteria_ = new HashMap<String,Object>();
		boolean isAdd = false;
		String fileDir = MessageUtil.getExtConfig("fj.course.template.url");//实际文件存放目录
		User user = (User) Common.findUserSession();
		
		int start_pos_x =0;
        int start_pos_y =0;
        int area_width = 0;
        int area_height = 0;
		String courseTemplateId = getParaValue("courseTemplateId");//附件id
		String posId = getParaValue("posId");
		String type = getParaValue("type");
		String sfsf = getParaValue("sfsf");//是否缩放
		Integer lx = Integer.parseInt(getParaValue("lx")); //类型： 0-特征点左侧  1-考号识别区 2-考号填涂采集区 3-客观题（单选） 4-客观题（多选） 5-主观题  9-缺考区域
		//判断新增还是编辑
    	if(StringUtils.isEmpty(posId)){
        	posId = UUIDUtils.UUID();//新增操作
        	isAdd = true;
        }
		if(StringUtils.isEmpty(type)){
			Integer x1 = StringUtils.isEmpty(getParaValue("x1"))?0:Integer.valueOf(getParaValue("x1"));
			Integer y1 = StringUtils.isEmpty(getParaValue("y1"))?0:Integer.valueOf(getParaValue("y1"));
			Integer x2 = StringUtils.isEmpty(getParaValue("x2"))?0:Integer.valueOf(getParaValue("x2"));
			Integer y2 = StringUtils.isEmpty(getParaValue("y2"))?0:Integer.valueOf(getParaValue("y2"));
	        Float width_bl = StringUtils.isEmpty(getParaValue("width_bl"))?0f:Float.valueOf(getParaValue("width_bl"));
	        if(sfsf.equals("true")){//还原真正坐标点
	            x1 = (int) Math.round(x1 / width_bl);
	            x2 = (int) Math.round(x2 / width_bl);
	            y1 = (int) Math.round(y1 / width_bl);
	            y2 = (int) Math.round(y2 / width_bl);
	        }
	        
	        //查询模板存储路径
	        criteria1.put("id", courseTemplateId);
			CourseTemplate entity = this.courseTemplateService.findEntity(criteria1);
			String sourceUrl = fileDir + entity.getFilePath();//模板存放路径
			
	        params.put("width", x2 - x1);
	        params.put("height", y2 -y1);
	        params.put("start_x", x1);
	        params.put("start_y", y1);
	        params.put("sourceUrl", sourceUrl);
	        
	        criteria_.put("owner", courseTemplateId);
	    	criteria_.put("lx", lx);
	    	criteria_.put("sourceUrl", sourceUrl);
	    	criteria_.put("params", params);
	    	
	        criteria.put("x1", x1);
	    	criteria.put("x2", x2);
	    	criteria.put("y1", y1);
	    	criteria.put("y2", y2);
		}
        String th = getParaValue("th");
        String zfz = getParaValue("zfz");
        String dtfz = getParaValue("dtfz");
        
        criteria.put("owner", courseTemplateId);
        criteria.put("area_title", getParaValue("areaTitle"));
        criteria.put("ms", getParaValue("ms")==null?"":getParaValue("ms"));
        criteria.put("lx", lx);
    	criteria.put("creator", user.getId());
    	if(lx==0){//特征点
    		if(StringUtils.isEmpty(type)){
    			//识别答卷定位点坐标
                BufferedImage image_pos = this.cropService.getCropImageBuffered(params);
                if(image_pos!=null){
                    Map<String,Object> map = pointRecognitionService.getAreaResult(image_pos,2);
                    start_pos_x = Integer.parseInt(map.get("start_x")+"");//图像内容实际起始点X
                    start_pos_y = Integer.parseInt(map.get("start_y")+"");//图像内容实际起始点Y
                }
    		}
        }else if(lx==1){//考号识别区,需要保存该区域考号的行数和列数
        	if(StringUtils.isEmpty(type)){
	            //计算考号区域实际大小
	            Map<String,Object> areaMap = pointRecognitionService.getKhAreaWidthHeight(params);
	            start_pos_x = Integer.parseInt(String.valueOf(areaMap.get("start_x")));//图像内容实际起始点X
	            start_pos_y = Integer.parseInt(String.valueOf(areaMap.get("start_y")));//图像内容实际起始点Y
	            area_width = Integer.parseInt(String.valueOf(areaMap.get("width")));
	            area_height = Integer.parseInt(String.valueOf(areaMap.get("height")));
        	}
        	criteria.put("row_count", getParaValue("rowCount"));
            criteria.put("col_count", getParaValue("colCount"));
        }else if(lx==2 || lx==6){
        	if(StringUtils.isEmpty(type)){
        		//填涂采集区 ,只有填涂区数量等于3个时才进行计算
        		Map<String,Object> m = updateSmallAreaInfo(criteria_);
        		area_width = m.get("area_width")==null?0:Integer.parseInt(String.valueOf(m.get("area_width")));
            	area_height = m.get("area_height")==null?0:Integer.parseInt(String.valueOf(m.get("area_height")));
        	}
        }else if(lx==3 || lx==4){//客观题（单选） 客观题（多选）
        	Integer daxxsl = Integer.parseInt(getParaValue("daxxsl"));
            Integer ksth = Integer.parseInt(getParaValue("ksth"));
            Integer jsth = Integer.parseInt(getParaValue("jsth"));
            int rows = 1;
            if(ksth != jsth){
                rows = jsth - ksth + 1;
            }
                
            //计算客观题标准区域实际大小-鼠标悬浮直接编辑只更新信息不更新坐标点
            if(StringUtils.isEmpty(type)){
            	Map<String,Object> areaMap = pointRecognitionService.getKhAreaWidthHeight(params);
            	area_width = Integer.parseInt(String.valueOf(areaMap.get("width")));
                area_height = Integer.parseInt(String.valueOf(areaMap.get("height")));
                start_pos_x = Integer.parseInt(String.valueOf(areaMap.get("start_x")));
                start_pos_y = Integer.parseInt(String.valueOf(areaMap.get("start_y")));
            }
            criteria.put("type", type);
            criteria.put("row_count", rows);
            criteria.put("col_count", daxxsl);
            criteria.put("dtfz", dtfz);
            criteria.put("ksth", ksth);
            criteria.put("jsth", jsth);
            criteria.put("xxsl", daxxsl);
            criteria.put("dtfzlx", getParaValue("dtfzlx"));
        }else if(lx==5){//主观题
        	criteria.put("th", th);
            criteria.put("zfz", zfz);
                
            //保存小题目信息
            List<Map<String,Object>> tmxxList = new ArrayList<Map<String,Object>>();
            String addIds = getParaValue("addIds");
            if(!StringUtils.isEmpty(addIds)){
                if(addIds.trim().endsWith(",")){
                    addIds = addIds.substring(0,addIds.length()-1);
                }
                String[] ids = addIds.split(",");
                for(int i=0;i<ids.length;i++){
                	Map<String,Object> map = new HashMap<String,Object>();
                	map.put("id", ids[i]);
                	map.put("owner", posId);
                	map.put("th", getParaValue("tmbh_"+ids[i]));
                	map.put("mc", getParaValue("tmmc_"+ids[i]));
                	map.put("fz", getParaValue("tmfz_"+ids[i]));
                	tmxxList.add(map);
                }
                this.courseTemplateService.insertMoreTmxx(tmxxList);
            }
            
            String editIds = getParaValue("editIds");//编辑小题
            if(!StringUtils.isEmpty(editIds)){
            	if(editIds.trim().endsWith(",")){
            		editIds = editIds.substring(0,editIds.length()-1);
                }
            	String[] ids = editIds.split(",");
            	for(int i=0;i<ids.length;i++){
                	Map<String,Object> map = new HashMap<String,Object>();
                	map.put("id", ids[i]);
                	map.put("owner", posId);
                	map.put("th", getParaValue("tmbh_"+ids[i]));
                	map.put("mc", getParaValue("tmmc_"+ids[i]));
                	map.put("fz", getParaValue("tmfz_"+ids[i]));
                	this.courseTemplateService.updateTmxx(map);
                }
            }
        }else if(lx==9){//缺考区域,计算缺考填涂区宽度和高度
        	if(StringUtils.isEmpty(type)){
	            Map<String,Object> areaMap = pointRecognitionService.getSingleAreaWidthHeight(params);
	            start_pos_x = Integer.parseInt(String.valueOf(areaMap.get("start_x")));
	            start_pos_y = Integer.parseInt(String.valueOf(areaMap.get("start_y")));
	            area_width = Integer.parseInt(String.valueOf(areaMap.get("singleWidth")));
	            area_height = Integer.parseInt(String.valueOf(areaMap.get("singleHeight")));
        	}
        }
    	if(StringUtils.isEmpty(type)){
	    	criteria.put("area_width", area_width);
	    	criteria.put("area_height", area_height);
	    	criteria.put("start_x", start_pos_x);
	        criteria.put("start_y", start_pos_y);
    	}
        criteria.put("id", posId);
        
        //执行保存数据
        try{
        	if(isAdd){
        		this.courseTemplateService.insertArea(criteria);
        	}else{
        		this.courseTemplateService.updateArea(criteria);
        	}
            result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
            logger.error("exec doSaveCropInfo method save data is success!!! exec method is doSaveCropInfo.");
        }catch(ServiceException ex){
        	result.setResultCode(ex.getErrorNo());
        	logger.error("exec doSaveCropInfo method save data is fail!!! exec method is doSaveCropInfo.", ex);
        }
		return result;
	}
	
	/**
	 * 更新截图区域坐标信息
	    * @Title: updateAreaPos
	    * @param @return    参数
	    * @return Result<?>    返回类型
	    * @throws
	 */
	/*@ResponseBody
	@RequestMapping("/updateAreaPos/exec")
	public Result<?> updateAreaPos() {
		Result<?> result = new Result<String>();
		String sfsf = getParaValue("sfsf");//是否缩放
		Integer x1 = StringUtils.isEmpty(getParaValue("x1"))?0:Integer.valueOf(getParaValue("x1"));
		Integer y1 = StringUtils.isEmpty(getParaValue("y1"))?0:Integer.valueOf(getParaValue("y1"));
		Integer x2 = StringUtils.isEmpty(getParaValue("x2"))?0:Integer.valueOf(getParaValue("x2"));
		Integer y2 = StringUtils.isEmpty(getParaValue("y2"))?0:Integer.valueOf(getParaValue("y2"));
        Float width_bl = StringUtils.isEmpty(getParaValue("width_bl"))?0f:Float.valueOf(getParaValue("width_bl"));
        if(sfsf.equals("true")){//还原真正坐标点
            x1 = (int) Math.round(x1 / width_bl);
            x2 = (int) Math.round(x2 / width_bl);
            y1 = (int) Math.round(y1 / width_bl);
            y2 = (int) Math.round(y2 / width_bl);
        }
        Map<String,Object> criteria = new HashMap<String,Object>();
        criteria.put("id", getParaValue("posId"));
        criteria.put("x1", x1);
        criteria.put("x2", x2);
        criteria.put("y1", y1);
        criteria.put("y2", y2);
        criteria.put("courseTemplateId", getParaValue("courseTemplateId"));
		try {
			this.courseTemplateService.updateAreaPos(criteria);
			result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
		} catch (ServiceException e) {
			result.setResultCode(e.getErrorNo());
		}
		result.setData(criteria);
		return result;
	}	*/
	
	/**
	 * @throws IOException 
	 * 计算保存3个小截图区域大小
	    * @Title: updateSmallAreaInfo
	    * @param @param criteria
	    * @param @return    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	public Map<String,Object> updateSmallAreaInfo(Map<String,Object> criteria) throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		List<CourseTemplateArea> list = this.courseTemplateService.getCourseTemplateAreaList(criteria);
        if(list.size()==2){
            CourseTemplateArea r1 = list.get(0);
            CourseTemplateArea r2 = list.get(1);
            Map<String,Object> map_ = new HashMap<String,Object>();
            map_.put("sourceUrl", criteria.get("sourceUrl"));
            map_.put("map3", criteria.get("params"));
            map_.put("map1", getAreaMap(r1,criteria.get("sourceUrl")));
            map_.put("map2", getAreaMap(r2,criteria.get("sourceUrl")));
            Map<String,Object> areaMap = pointRecognitionService.getAreaWidthHeight(map_);
            int singleWidth = Integer.parseInt(String.valueOf(areaMap.get("singleWidth")));
            int singleHeight = Integer.parseInt(String.valueOf(areaMap.get("singleHeight")));
            map.put("area_width", singleWidth);
            map.put("area_height", singleHeight);
            
            //更新客观题采集记录填涂区大小
            List<String> idList = new ArrayList<String>();
            idList.add(r1.getId());
            idList.add(r2.getId());
            Map<String,Object> criteria_ = new HashMap<String,Object>();
            criteria_.put("singleWidth", singleWidth);
            criteria_.put("singleHeight", singleHeight);
            criteria_.put("ids", idList);
            this.courseTemplateService.updateKhttcjAreaInfo(criteria_);
        }
        return map;
	}
	
	/**
	 * 查询题目编号是否重复
	    * @Title: checkThExists
	    * @param @return    参数
	    * @return Result<?>    返回类型
	    * @throws
	 */
	@ResponseBody
	@RequestMapping("/checkThExists")
	public Result<?> checkThExists() {
		Result<?> result = new Result<String>();
		try {
			Map<String,Object> criteria = new HashMap<String,Object>();
	        String type = getParaValue("type");
	        criteria.put("id1", getParaValue("id"));
	        criteria.put("th", getParaValue("th"));
	        if(!StringUtils.isEmpty(getParaValue("id"))){
    			criteria.put("exclSelf", true);
    		}
        	if(type.equals("1")){
        		//大题
        		criteria.put("owner", getParaValue("courseTemplateId"));
        		boolean flag = this.courseTemplateService.checkThExistsForArea(criteria);
        		if(!flag){
        			result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
        		}
        	}else{
        		//小题
        		criteria.put("owner", getParaValue("parentId"));
        		boolean flag = this.courseTemplateService.checkThExistsForTmxx(criteria);
        		if(!flag){
        			result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
        		}
        	}
		} catch (ServiceException e) {
			result.setResultCode(e.getErrorNo());
		}
		return result;
	}
	
	/**
	 * 查询单选题起始题号是否存在
	    * @Title: checkQsthExists
	    * @param @return    参数
	    * @return Result<?>    返回类型
	    * @throws
	 */
	@ResponseBody
	@RequestMapping("/checkQsthExists")
	public Result<?> checkQsthExists() {
		Result<?> result = new Result<String>();
		try {
			Map<String,Object> criteria = new HashMap<String,Object>();
	        criteria.put("ksth", getParaValue("ksth"));
	        criteria.put("jsth", getParaValue("jsth"));
	        criteria.put("id1", getParaValue("posId"));
	        criteria.put("lx", getParaValue("lx"));
	        criteria.put("owner", getParaValue("courseTemplateId"));
	        criteria.put("filterTh", true);
	        if(!StringUtils.isEmpty(getParaValue("posId"))){
    			criteria.put("exclSelf", true);
    		}
    		boolean flag = this.courseTemplateService.checkQsthExistsForArea(criteria);
    		if(!flag){
    			result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
    		}
		} catch (ServiceException e) {
			result.setResultCode(e.getErrorNo());
		}
		return result;
	}
	
	/**
     * 获取记录结果map
     * @param r 记录
     * @return
     * @see   [类、类#方法、类#成员]
     * @since [产品/模块版本]
     */
    public Map<String,Object> getAreaMap(CourseTemplateArea entity,Object url){
        Map<String,Object> map = new  HashMap<String,Object>();
        int x1 = Integer.parseInt(entity.getX1());
        int x2 = Integer.parseInt(entity.getX2());
        int y1 = Integer.parseInt(entity.getY1());
        int y2 = Integer.parseInt(entity.getY2());
        map.put("width", x2-x1);
        map.put("height", y2-y1);
        map.put("start_x", x1);
        map.put("start_y", y1);
        map.put("sourceUrl", url);
        return map;
    }
    
    @ResponseBody
    @RequestMapping("/deleteOldTemp/exec")
    public Result<?> deleteOldTemp(@RequestBody Map<String,Object> criteria){
    	Result<?> result = new Result<String>();
    	try{
    		this.courseTemplateService.deleteTemplate(criteria);
    		result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
    	}catch(ServiceException e){
    		result.setResultCode(e.getErrorNo());
    	}
    	return result;
    }
    
	class Views {
		/**
		 * index视图
		 */
		public static final String LIST_INDEX = "/manage/courseTemplate/list";
		
		/**
		 * 列表视图
		 */
		public static final String LIST_VIEW = "/manage/courseTemplate/list";

		/**
		 * 编辑视图
		 */
		public static final String EDIT_VIEW = "/manage/courseTemplate/edit";
		
		/**
		 * 上传视图
		 */
		public static final String UPLOAD_VIEW = "/manage/courseTemplate/upload";
		
		/**
		 * 裁剪主视图
		 */
		public static final String JCROP_INDEX_VIEW = "/manage/courseTemplate/crop_index";
		
		/**
		 * 裁剪编辑视图
		 */
		public static final String EDIT_AREA_PROP_VIEW = "/manage/courseTemplate/edit_prop";
	}
}
